﻿using System;
using System.Collections.Concurrent;
using System.IO;

namespace Zjh.PackSerializer.Converters
{
    public abstract class PackConverter : IPackConverter
    {
        public static ConcurrentDictionary<Type, PackContract> PackContractMap { get; } = new ConcurrentDictionary<Type, PackContract>();

        static PackConverter()
        {
            foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (var type in asm.GetTypes())
                {
                    var pc = PackContract.TryCreateInstance(type);
                    if (pc != null)
                    {
                        PackContractMap[type] = pc;
                    }
                }
            }
        }

        public virtual bool CanConvert(Type objectType)
        {
            return false;
        }

        public virtual bool Read(Stream stream, Type objectType, IPackSerializer serializer, out object output)
        {
            output = null;
            return CanConvert(objectType);
        }

        public virtual bool Write(Stream stream, Type objectType, object input, IPackSerializer serializer)
        {
            return CanConvert(objectType);
        }
    }
}